package archer.framework.utils;

import archer.framework.core.exception.BaseException;
import jodd.jerry.Jerry;
import jodd.lagarto.dom.LagartoDOMBuilder;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Jerry工具类
 *
 * @author christ
 * @date 2016/3/2
 */
public class JerryUtils {

    /**
     * xml模式解析
     *
     * @param content
     * @return
     */
    public static Jerry xmlJerry(String content) {
        LagartoDOMBuilder domBuilder = new LagartoDOMBuilder();
        domBuilder.enableXmlMode();
        return Jerry.jerry(domBuilder).parse(content);
    }

    /**
     * html模式解析
     *
     * @param content
     * @return
     */
    public static Jerry htmlJerry(String content) {
        LagartoDOMBuilder domBuilder = new LagartoDOMBuilder();
        domBuilder.enableHtmlMode();
        return Jerry.jerry(domBuilder).parse(content);
    }

    /**
     * xhtml模式解析
     *
     * @param content
     * @return
     */
    public static Jerry xhtmlJerry(String content) {
        LagartoDOMBuilder domBuilder = new LagartoDOMBuilder();
        domBuilder.enableXhtmlMode();
        return Jerry.jerry(domBuilder).parse(content);
    }


    /**
     * html-plus模式解析
     *
     * @param content
     * @return
     */
    public static Jerry htmlPlusJerry(String content) {
        LagartoDOMBuilder domBuilder = new LagartoDOMBuilder();
        domBuilder.enableHtmlPlusMode();
        return Jerry.jerry(domBuilder).parse(content);
    }

    public static <T> String toXML(Object o, Class<T> valueType) {

        try {
            Marshaller marshaller = JAXBContext.newInstance(valueType).createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
            StringWriter writer = new StringWriter();
            marshaller.marshal(o, writer);
            return writer.toString();
        } catch (JAXBException e) {
            throw new BaseException(e.getMessage(), e);
        }
    }

    public static <T> T fromXML(String xml, Class<T> valueType) {
        try {
            Unmarshaller unmarshaller = JAXBContext.newInstance(valueType).createUnmarshaller();
            return (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }
}
